﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CSharpStudy
{
    public class AttributeTest
    {
        //public static void Main(string[] arges)
        //{
        //    Goods g=new Goods(){GoodsName = "张是哪323232"};
        //    Validate.IsValidate(g);
        //    Console.ReadLine();
        //}
    }
    [AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Method|AttributeTargets.Property)]
    public sealed class MyStringLenthAttribute :Attribute
    {
        public string Contenet { get; private set; }

        public int MaxLenth { get; private set; }

        public int MinLenth { get; set; }

        public string ErrorMsg { get; set; }

        public MyStringLenthAttribute(string iContent,int iMaxLenth)
        {
            Contenet = iContent;
            MaxLenth = iMaxLenth;
        }
    }

    public class Goods
    {
        [MyStringLenth("",5,MinLenth = 2,ErrorMsg = "{0}的长度必须在{1}和{2}之间!")]
        public string GoodsName { get; set; }
    }

    public class Validate
    {
        private static bool ValidateLenth(int inputLenth,MemberInfo member)
        {
            foreach (var attri in member.GetCustomAttributes(true))
            {
                if (attri is MyStringLenthAttribute)
                {
                    var CurrentAttri = attri as MyStringLenthAttribute;
                    string displayName = CurrentAttri.Contenet;
                    int maxLenth = CurrentAttri.MaxLenth;
                    int minLenth = CurrentAttri.MinLenth;
                    string errorMsg = CurrentAttri.ErrorMsg;
                    if (inputLenth>maxLenth||inputLenth<minLenth)
                    {
                        Console.WriteLine(errorMsg,displayName,minLenth,maxLenth);
                        return false;
                    }
                }
            }
            return true;
        }

        public static bool IsValidate(Goods goods)
        {
            if (goods == null) return false;

            foreach (var good in typeof(Goods).GetProperties())
            {
                if (ValidateLenth(goods.GoodsName.Length,good))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
